package listbyorder.access001_100.test25;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/29 15:17
 */
public class Solution1 {

    // 方法一————递归求解
    public ListNode reverseKGroup(ListNode head, int k) {
        if (k == 1 || head == null) return head;
        return getAns(head, k);
    }

    private ListNode getAns(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        ListNode temp = head;
        int i = k;   // 注意，这里必须要定义新的变量获取k值，否则会出错
        while (i - 1 > 0) {
            temp = temp.next;
            if (temp == null) {
                return head;
            }
            i--;
        }
        ListNode next = temp.next;
        temp.next = null;
        // 反转当前的前链表
        ListNode new_head = reverse(head);
        head.next = getAns(next, k);
        return new_head;
    }

    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
